package com.rongke.web.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.annotation.SourceAuthority;
import com.rongke.commons.FailException;
import com.rongke.commons.JsonResp;
import com.rongke.commons.PageDto;
import com.rongke.enums.SourceType;
import com.rongke.mapper.UserMapper;
import com.rongke.model.*;
import com.rongke.service.*;
import com.rongke.sms.SmsService;
import com.rongke.sms.SmsTempletEnum;
import com.rongke.utils.DateUtils;
import com.rongke.utils.Md5;
import com.rongke.utils.OrderUtils;
import com.rongke.utils.RandomUtils;
import com.rongke.web.apix.*;
import com.rongke.web.lianpay.ConfirmPaymentApi;
import com.rongke.web.lianpay.FenqiPayment;
import com.rongke.web.lianpay.PaymentApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.rongke.web.apix.YYSDemo.getCapcha;
import static jxl.biff.FormatRecord.logger;

/**
 * @version : Ver 1.0
 * @UserController
 * @用户基本信息Controller
 */
@RestController
@RequestMapping(value = "/api/user")
@Transactional
@CrossOrigin(origins = "*",maxAge = 3600)
public class UserController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userDao;
    @Autowired
    private UserAuthService userAuthService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private ParamSettingService paramSettingService;
    @Autowired
    private LoanOrderService loanOrderService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private UserCouponService userCouponService;
    @Autowired
    private UserPhoneRecordService userPhoneRecordService;
    @Autowired
    private UserIdentityService userIdentityService;
    @Autowired
    private UserBankService userBankService;
    @Autowired
    private UserPhoneService userPhoneService;
    @Autowired
    private UserTaobaoAddressService userTaobaoAddressService;
    @Autowired
    private UserJindongAddressService userJindongAddressService;
    @Autowired
    private UserTaobaoZhifubaoService userTaobaoZhifubaoService;
    @Autowired
    private PersonRecordService personRecordService;
    @Autowired
    private PayOrderConfirmService payOrderConfirmService;
    @Autowired
    private MsgModelService msgModelService;

    @Autowired
    private UserJingdongService userJingdongService;

    private final static Map keymap = new HashMap<String, Object>();

    private static String WX_APPID="wx5e79852c81693d46";
    private static String WX_APPSECRET="11407a16ebc90d04a226efef75053084";


    /**
     * @param user
     * @return 返回值JsonResp
     * @添加用户基本信息
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResp addUser(@RequestBody User user) {
        log.debug("添加用户基本信息");
        if(null==user.getId()){
            userService.insert(user);
       /*     //添加用户到认证信息表
            UserAuth ua = new UserAuth();
            ua.setUserId(user.getId());
            userAuthService.insert(ua);*/
        }else{
            userService.updateById(user);
        }
        return JsonResp.ok(user);
    }


    /**
     * 获取微信openid
     * @param code
     * @return
     */
    @RequestMapping(value = "/getOpenid", method = RequestMethod.GET)
    public JsonResp getOpenid(String code) {
        String str = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+WX_APPID+"&secret="+WX_APPSECRET+"&code=" + code + "&grant_type=authorization_code";
        JSONObject jsonObject=null;
        String openId = "";
        String access_token = "";
        try {
            URL getUrl = new URL(str);
            HttpURLConnection http = (HttpURLConnection) getUrl.openConnection();
            http.setRequestMethod("GET");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] b = new byte[size];
            is.read(b);
            String message = new String(b, "UTF-8");
            JSONObject json = JSONObject.parseObject(message);
//            log.debug(code);
//            log.debug(json);
            openId = json.getString("openid");
            access_token=json.getString("access_token");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (openId != "" && openId!=null) {
            EntityWrapper ew = new EntityWrapper();
            ew.eq("openid", openId);
            User user = userService.selectOne(ew);
            if (user != null) {
//                jsonObject= getUserMessage(access_token,openId);

                System.out.print("json.........................."+jsonObject);

                EntityWrapper<UserAuth> ewua=new EntityWrapper<>();
                ewua.eq("user_id",user.getId());
                UserAuth ua=userAuthService.selectOne(ewua);
                user.setUserAuth(ua);//前台以此判断认证到哪一步

                return JsonResp.ok(user);
            } else {
                User user1 = new User();
                user1.setOpenid(openId);
                userService.insert(user1);
                user1=userService.selectById(user1.getId());
                //添加用户到认证信息表
                UserAuth ua = new UserAuth();
                ua.setUserId(user1.getId());
                userAuthService.insert(ua);
                ua=userAuthService.selectById(ua.getId());
                user1.setUserAuth(ua);
//                jsonObject= getUserMessage(access_token,openId);
                System.out.print("json.........................."+jsonObject);
                return JsonResp.ok(user1);
            }
        }else{
            return JsonResp.fa("无返回");
        }

    }


    public JSONObject getUserMessage(String access_token,String openid){
        log.error("******access_token="+access_token+",,,,,openid="+openid+"**********");
        String str = "https://api.weixin.qq.com/sns/userinfo?access_token= "+access_token+"&openid="+openid;
        JSONObject json=null;
        try {
            URL getUrl = new URL(str);
            HttpURLConnection http = (HttpURLConnection) getUrl.openConnection();
            http.setRequestMethod("GET");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] b = new byte[size];
            is.read(b);
            String message = new String(b, "UTF-8");
            json = JSONObject.parseObject(message);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }



        return json;
    }


    /**
     * @param
     * @return 返回值JsonResp
     * @用户是否设置过交易密码
     */
    @SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/payPwdIsExist", method = RequestMethod.GET)
    public JsonResp payPwdIsExist() {
        log.debug("用户是否设置过交易密码");
        User user = userService.findLoginUser();
        if (null == user.getPayPwd()) {
            return JsonResp.ok("false");
        } else {
            return JsonResp.ok("true");
        }
    }

    /**
     * @param
     * @return 返回值JsonResp
     * @设置交易密码
     */
    @SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/payPwdSetting", method = RequestMethod.GET)
    public JsonResp payPwdSetting(String payPwd, String payPwdConfirm) {
        log.debug("设置交易密码");
        if (payPwd.equals(payPwdConfirm) && payPwd != null && !payPwd.equals("")) {
            User user = userService.findLoginUser();
            user.setPayPwd(payPwd);
            userService.updateById(user);
            return JsonResp.ok();
        } else {
            return JsonResp.fa("密码不一致！");
        }

    }

    /**
     * @param
     * @return 返回值JsonResp
     * @旧交易密码验证
     */
    @SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/oldPayPwdConfirm", method = RequestMethod.GET)
    public JsonResp oldPayPwdConfirm(String oldPayPwd) {
        log.debug("旧交易密码验证");
        User user = userService.findLoginUser();
        if (user.getPayPwd().equals(oldPayPwd)) {
            return JsonResp.ok();
        } else {
            return JsonResp.fa("密码不正确！");
        }

    }

    /**
     * @param user
     * @return 返回值JsonResp
     * @修改用户基本信息
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResp updateUser(@RequestBody User user) {
        log.debug("修改用户基本信息");
        userService.updateById(user);
        return JsonResp.ok(user);
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @根据id查找用户基本信息
     */
    @RequestMapping(value = "/selectOne", method = RequestMethod.GET)
    public JsonResp selectUser(Long id) {
        log.debug("查找用户基本信息");
        User user = userService.selectById(id);
        return JsonResp.ok(user);
    }


    /**
     * @param phone    手机号
     * @param password 密码
     * @return JsonResp
     * @throws UnsupportedEncodingException
     * @登录
     */
    @RequestMapping(value = "/loginPhone", method = RequestMethod.GET)
    public JsonResp loginByPhone(String phone, String password, String phoneSign) throws UnsupportedEncodingException {
        log.debug("登录");
        User user = userDao.selectByPhone(phone);
        if (user == null) {
            return JsonResp.fa("该用户不存在！");
        }
//        else if(user.getStatus()!=1){
//            return JsonResp.fa("该用户已不可用！");
//        }
        return userService.loginByPhone(URLDecoder.decode(phone, "utf-8"), password, phoneSign);
    }

    /**
     * @注销
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public JsonResp logout() {
        log.debug("注销");
        userService.logout();
        return JsonResp.ok();
    }

    /**
     * @return 返回值JsonResp
     * @用户首页信息
     */
    @RequestMapping(value = "/userFirstPage", method = RequestMethod.GET)
    public JsonResp getUserFirstPage(BigDecimal userMoney, Integer limitDays,Long userId) {
        log.debug("用户首页信息");
//        User user = userService.findLoginUser();
        User user = userService.selectById(userId);
        Map map = new HashMap();
        //用户是否有还款中订单
        if (user.getIsPay() == 0) {
            if (null == userMoney) {
                userMoney = user.getMoney();
            }
            //算出费用
            EntityWrapper<ParamSetting> ew = new EntityWrapper<>();
            if (null == limitDays) {
                limitDays = 7;
            }
            ew.eq("limit_days", limitDays);
            ew.eq("status", 1);
            ParamSetting paramSetting = paramSettingService.selectOne(ew);
            BigDecimal interestMoney = userMoney.multiply(BigDecimal.valueOf(paramSetting.getInterestPercent() / 1000));
            BigDecimal placeServeMoney = userMoney.multiply(BigDecimal.valueOf(paramSetting.getPlaceServePercent() / 100));
            BigDecimal msgAuthMoney = userMoney.multiply(BigDecimal.valueOf(paramSetting.getMsgAuthPercent() / 100));
            BigDecimal riskServePercent = userMoney.multiply(BigDecimal.valueOf(paramSetting.getRiskServePercent() / 100));
            BigDecimal riskPlanPercent = userMoney.multiply(BigDecimal.valueOf(paramSetting.getRiskPlanPercent() / 100));
            BigDecimal allWasteMoney = interestMoney.add(placeServeMoney).add(msgAuthMoney).add(riskServePercent).add(riskPlanPercent);
            BigDecimal realMoney = userMoney.subtract(allWasteMoney);

            map.put("userMoney", user.getMoney());
            map.put("realMoney", realMoney);
            map.put("interestMoney", interestMoney);
            map.put("allWasteMoney", allWasteMoney);
            map.put("placeServeMoney", placeServeMoney);
            map.put("msgAuthMoney", msgAuthMoney);
            map.put("riskServePercent", riskServePercent);
            map.put("riskPlanPercent", riskPlanPercent);
            map.put("isPay", "true");
        } else {
            //有还款订单时
            EntityWrapper<LoanOrder> ew = new EntityWrapper<>();
            ew.eq("user_id", user.getId());
            List<Integer> list = new ArrayList<Integer>() {{
                add(1);
                add(2);
                add(3);
                add(4);
                add(5);
            }};
            ew.in("order_status", list);
            LoanOrder loanOrder = loanOrderService.selectOne(ew);
            BigDecimal needPayMoney = loanOrder.getNeedPayMoney();
            BigDecimal borrowMoney = loanOrder.getBorrowMoney();
            Date gmtDatetime = loanOrder.getGmtDatetime();
            Date limitPayTime = loanOrder.getLimitPayTime();
            map.put("needPayMoney", needPayMoney);
            map.put("borrowMoney", borrowMoney);
            map.put("gmtDatetime", gmtDatetime);
            map.put("limitPayTime", limitPayTime);
            map.put("isPay", "false");
            map.put("orderId", loanOrder.getId());
        }

        return JsonResp.ok(map);
    }

    /**
     * @注册用户
     */
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public JsonResp register(String phone, String password, String code, String uuid) {
        if (keymap.get("code") == null || code == null || !code.equals(keymap.get("code").toString())) {
            return JsonResp.fa("验证码错误");
        }
        EntityWrapper<User> ew = new EntityWrapper<User>();
        ew.eq("phone", phone);
        List<User> users = userService.selectList(ew);
        if (users.size() <= 0) {
            User user = new User();
            user.setPhone(phone);
            user.setPassword(Md5.md5Encode(password));
            boolean boo = userService.insert(user);
            //添加用户验证表
            UserAuth userAuth = new UserAuth();
            userAuth.setUserId(user.getId());
            userAuthService.insert(userAuth);
            //新客优惠券
            EntityWrapper<Coupon> ew4 = new EntityWrapper<>();
            ew4.eq("type", 1);
            ew4.eq("coupon_status", 1);
            Coupon firstCoupon = couponService.selectOne(ew4);
            if (firstCoupon != null) {
                UserCoupon userCoupon = new UserCoupon();
                userCoupon.setUserId(user.getId());
                userCoupon.setCouponId(firstCoupon.getId());
                userCoupon.setSaveMoney(firstCoupon.getSaveMoney());
                userCouponService.insert(userCoupon);
                //会员总数加一
                EntityWrapper<PersonRecord> ewPserson = new EntityWrapper();
                PersonRecord personRecord = personRecordService.selectOne(ewPserson);
                personRecord.setMemberCount(personRecord.getMemberCount() + 1);
                personRecordService.updateById(personRecord);
                //用户优惠券总数加一
                user.setCouponAllCount(1);
                userService.updateById(user);
            }
            //邀请好友奖励
            if (uuid != null) {
                EntityWrapper ew2 = new EntityWrapper<>();
                ew2.eq("uuid", uuid);
                User shareUser = userService.selectOne(ew2);
                if (shareUser != null && shareUser.getStatus() == 1) {
                    UserCoupon shareUserCoupon = new UserCoupon();
                    shareUserCoupon.setUserId(shareUser.getId());
                    EntityWrapper<Coupon> ew3 = new EntityWrapper<>();
                    ew3.eq("type", 2);
                    ew3.eq("coupon_status", 1);
                    Coupon sharecoupon = couponService.selectOne(ew3);
                    if (sharecoupon != null) {
                        shareUserCoupon.setCouponId(sharecoupon.getId());
                        shareUserCoupon.setSaveMoney(sharecoupon.getSaveMoney());
                        shareUserCoupon.setInviteePhone(user.getPhone());
                        userCouponService.insert(shareUserCoupon);
                        //邀请者优惠券总数加一
                        shareUser.setCouponAllCount(shareUser.getCouponAllCount() + 1);
                        userService.updateById(shareUser);

                    }

                }
            }
            return JsonResp.ok(boo);

        } else {
            return JsonResp.fa("该号码已被注册！");
        }
    }

    /**
     * @return 返回值JsonResp
     * @获取验证码
     */
    @RequestMapping(value = "/getPhoneCode", method = RequestMethod.GET)
    public JsonResp getPhoneCode(String phone) {
        log.debug("获取验证码");
        SmsService.SmsTemplate.SmsContentCode smsContentCode = smsService.smsCodeByType(phone, 1);
        keymap.put("code", smsContentCode.getCode());
        return JsonResp.ok(keymap.get("code"));
    }

    /**
     * @param
     * @return 返回值JsonResp
     * @忘记密码
     */
    @SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/updatePasswordPhone", method = RequestMethod.GET)
    public JsonResp<?> updatePasswordPhone(String phone, String code, String password) {
        log.debug("忘记密码");
        EntityWrapper<User> ew = new EntityWrapper();
        ew.eq("phone", phone);
        User user = userService.selectOne(ew);
        if (user == null) {
            return JsonResp.fa("手机号码不存在！！");
        } else {
            if (keymap.get("code") == null || code == null || !code.equals(keymap.get("code").toString())) {
                return JsonResp.fa("验证码错误");
            } else {
                user.setPassword(Md5.md5Encode(password));
                userService.updateById(user);
                return JsonResp.ok("修改成功");
            }
        }
    }

    /**
     * @return 返回值JsonResp
     * @分享链接参数
     */
    @SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/shareUrlParam", method = RequestMethod.GET)
    public JsonResp shareUrlParam() {
        log.debug("分享链接参数");
        User user = userService.findLoginUser();
        return JsonResp.ok(user.getUuid());
    }

    /**
     * @param
     * @return 返回值JsonResp
     * @查询所有的用户列表
     */
    @RequestMapping(value = "/selectUserList", method = RequestMethod.GET)
    public JsonResp selectUserList(Page page, String authStatus, String phone, String userName, String status) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        userEntityWrapper.orderBy("gmt_datetime", false);
        if (status != null && !"".equals(status)) {
            userEntityWrapper.eq("status", status);
        }

        if (authStatus != null && !"".equals(authStatus)) {
            userEntityWrapper.eq("auth_status", authStatus);
        }
        if (phone != null && !"".equals(phone)) {
            userEntityWrapper.like("phone", phone);
        }
        if (userName != null && !"".equals(userName)) {
            userEntityWrapper.like("user_name", userName);
        }
        // userEntityWrapper.in("status",new ArrayList<Integer>(){{add(1);add(2);}});
        //  List<User> userList=userService.selectList(userEntityWrapper);
        //return JsonResp.ok(new PageDto(page.getCurrent(), page.getSize(), userList, userList.size()));
        Page<User> userPage = userService.selectPage(page, userEntityWrapper);
        return JsonResp.dataPage(userPage);
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @禁用用户
     */
    @RequestMapping(value = "/GoDeleteUpdate", method = RequestMethod.GET)
    public JsonResp GoDeleteUpdate(Long id) {
        User user = new User();
        user.setId(id);
        user.setStatus(3);
        Boolean boo = userService.updateById(user);

        return JsonResp.ok(boo);
    }


    /**
     * @param id
     * @return 返回值JsonResp
     * @拉黑用户
     */
    @RequestMapping(value = "/GoDeleteUpdate1", method = RequestMethod.GET)
    public JsonResp GoDeleteUpdate1(Long id) {
        User user = userService.selectById(id);
        if (user.getStatus().equals(3)) {
            return JsonResp.fa("操作不合法");
        } else {
            user.setId(id);
            user.setStatus(2);
            Boolean boo = userService.updateById(user);

            return JsonResp.ok(boo);
        }
    }


    /**
     * @return 返回值JsonResp
     * @用户是否能借款
     */
    @SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/userIsBorrow", method = RequestMethod.GET)
    public JsonResp userIsBorrow() {
        log.debug("用户是否能借款");
        User user = userService.findLoginUser();
        if (user.getAuthStatus() == 1) {
            return JsonResp.ok("true");
        } else {
            return JsonResp.fa("false");
        }
    }

    @SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/userIsRefuse", method = RequestMethod.GET)
    public JsonResp userIsRefuse() {
        User user = userService.findLoginUser();
        if (user.getStatus() == 1) {
            return JsonResp.ok("true");
        } else {
            return JsonResp.fa("false");
        }
    }


    /**
     * @return 返回值JsonResp
     * @用户首页的类型
     */
    @SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/userFirstPageType", method = RequestMethod.GET)
    public JsonResp userFirstPageType() {
        log.debug("用户首页的类型");
        User user = userService.findLoginUser();
        if (user.getIsPay() == 0) {
            return JsonResp.ok("true");
        } else {
            return JsonResp.ok("false");
        }
    }

    /**
     * @return 返回值JsonResp
     * @运营商获取验证码
     */
    @RequestMapping(value = "/getSmsCodePhoneConfirm", method = RequestMethod.GET)
    public JsonResp getSmsCodePhoneConfirm(String phoneNo, String passwd) throws IOException {
        log.debug("运营商获取验证码");
        User user = userService.findLoginUser();
        if (user.getPhone().equals(phoneNo)) {
            String resp = getCapcha(phoneNo);

            JSONObject json = new JSONObject();
            json = json.parseObject(resp);
            String retCode = json.getString("errorCode");

            if (StringUtils.equals(retCode, "0")) {
                String codeType = json.getString("imgUrl");
                if (StringUtils.isBlank(codeType)) {
                    //部分手机及需要进一步操作
                    //String callback = "http://666456.tunnel.qydev.com/api/user/getReport?userId="+user.getId()+"";
                    String callback = "http://app.hzrywl.com/api/api//user/getReport?userId=" + user.getId() + "";
                    String loginResp = YYSDemo.login(phoneNo, passwd, "", callback);
                    json = new JSONObject();
                    json = json.parseObject(loginResp);
                    retCode = json.getString("errorCode");
                    Boolean isFinish = json.getBoolean("result");
                    if (isFinish) {
                        //存储user_phone表
                        //User user = userService.selectById(71);
                        EntityWrapper<UserPhone> ewPhone = new EntityWrapper();
                        ewPhone.eq("user_id", user.getId());
                        UserPhone userPhone = userPhoneService.selectOne(ewPhone);
                        if (userPhone == null || userPhone.equals("")) {
                            userPhone = new UserPhone();
                            userPhone.setPhone(phoneNo);
                            userPhone.setUserId(user.getId());
                            userPhoneService.insert(userPhone);
                        } else {
                            userPhone.setPhone(phoneNo);
                            userPhoneService.updateById(userPhone);
                        }
                        //授权完毕改变状态
                        EntityWrapper<UserAuth> ew = new EntityWrapper();
                        ew.eq("user_id", user.getId());
                        UserAuth userAuth = userAuthService.selectOne(ew);
                        userAuth.setPhoneAuth(1);
                        userAuthService.updateById(userAuth);
                        //改变user_phone表状态
                        userPhone.setStatus(1);
                        userPhoneService.updateById(userPhone);
                        return JsonResp.ok("登录不需要验证码");
                    } else if (StringUtils.equals(retCode, "0")) {
                        //发送验证码
                        String coderesp = YYSDemo.getSmsCode(phoneNo);
                        json = new JSONObject();
                        json = json.parseObject(coderesp);
                        retCode = json.getString("errorCode");
                        if (StringUtils.equals(retCode, "0")) {
                            return JsonResp.ok("第二种方式");//表示授权时走第五步
                        } else {
                            return JsonResp.fa("请求失败！ | [%s]" + json.getString("errorMsg"));
                        }
                    } else {
                        return JsonResp.fa("请求失败！ | [%s]" + json.getString("errorMsg"));
                    }
                } else if (!codeType.equals("smsCode")) {
                    return JsonResp.fa("该区域手机号暂时无法支持！");
                }
            } else {
                return JsonResp.fa("请求失败！ | [%s]" + json.getString("errorMsg"));
            }
            return JsonResp.ok();
        } else {
            return JsonResp.fa("该手机号与登录手机号不一致！");
        }

    }

    @Autowired
    private YYSLogService yysLogService;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private MobileService mobileService;

    /**
     * @return 返回json
     * @同盾运营商接口 第一阶段
     */
    @RequestMapping(value = "/mobileAuth1", method = RequestMethod.GET)
    public JsonResp mobileAuth(String phoneNo, String passwd, Long userId) {
        if (userId == null) {
            return JsonResp.toFail("userId不能为空");
        }
        Map<String, String> restMap = new HashMap<>();
        YYSLog t = new YYSLog();
        try {
//            User user = userService.findLoginUser();
            EntityWrapper<UserIdentity> ew = new EntityWrapper();
            ew.eq("user_id", userId);
            UserIdentity userIdentity = userIdentityService.selectOne(ew);
            String idcard = "";
            String userName = "";
            if (userIdentity != null) {
                idcard = userIdentity.getIdentityNum();
                userName = userIdentity.getUserName();
            }
            JSONObject createResultMap = TongdunYYSAuth.createTask(userName, idcard, phoneNo);
            Integer code = (Integer) createResultMap.get("code");
            if (createResultMap != null && code == 0) {
                t.setUserId(userId);
                t.setCode(createResultMap.getString("code"));
                t.setMessage(createResultMap.getString("message"));
                t.setTaskId(createResultMap.getString("task_id"));
                JSONObject dataJO = JSON.parseObject(createResultMap.getString("data"));
                t.setMobile(phoneNo);
                t.setCreatedTime(dataJO.getString("created_time"));
                EntityWrapper<YYSLog> ew2 = new EntityWrapper<YYSLog>();
                Map<String, Object> map2 = new HashMap<>();
                map2.put("user_id", t.getUserId());
                yysLogService.deleteByMap(map2);
                yysLogService.insert(t);
                JSONObject initResultJO = TongdunYYSAuth.acquire(t.getTaskId(), phoneNo, passwd, "INIT", "submit", null);
                restMap.put("code", initResultJO.getString("code"));
                restMap.put("message", initResultJO.getString("message"));
                restMap.put("taskId", initResultJO.getString("task_id"));
                String data = initResultJO.getString("data");
                if (StringUtils.isNotEmpty(data)) {
                    JSONObject dJO = JSON.parseObject(data);
                    restMap.put("nextStage", dJO.getString("next_stage"));
                    if ("101".equals(restMap.get("code"))) {
                        restMap.put("authCode", dJO.getString("auth_code"));
                    }
                }
                EntityWrapper<UserPhone> ewPhone = new EntityWrapper();
                ewPhone.eq("user_id", userId);
                UserPhone userPhone = userPhoneService.selectOne(ewPhone);
                if (userPhone == null || userPhone.equals("")) {
                    userPhone = new UserPhone();
                    userPhone.setPhone(phoneNo);
                    userPhone.setUserId(userId);
                    userPhoneService.insert(userPhone);
                } else {
                    userPhone.setPhone(phoneNo);
                    userPhoneService.updateById(userPhone);
                }

            } else {
                restMap.put("code", createResultMap.getString("code"));
                restMap.put("message", "认证失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            restMap.put("code", "9999");
            restMap.put("message", "系统错误");
        } finally {
            log.info("+++++++++++++++++++++++11111111111111111111111111:" + JsonResp.ok(restMap));
            return JsonResp.ok(restMap);
        }
    }

    /**
     * @return 返回json
     * @同盾运营商接口 第二阶段
     */
    @RequestMapping(value = "/mobileAuth2", method = RequestMethod.GET)
    public JsonResp mobileAuth2(String taskId, String passwd, String nextStage, String code, String txt, String phoneNo, Long userId) {
        Map<String, String> restMap = new HashMap<>();
        try {
            Map<String, String> map = new HashMap<>();
            JSONObject initResultJO = null;
            if ("100".equals(code)) {
                if (nextStage == null || nextStage == "") {
                    nextStage = "LOGIN";
                }
                initResultJO = TongdunYYSAuth.acquire(taskId, phoneNo, passwd, nextStage, "query", map);
            } else if ("101".equals(code) || "105".equals(code)) {
                if ("101".equals(code)) {
                    map.put("auth_code", txt);
                } else {
                    map.put("sms_code", txt);
                }
                initResultJO = TongdunYYSAuth.acquire(taskId, phoneNo, passwd, nextStage, "submit", map);
            }
            restMap.put("code", initResultJO.getString("code"));
            restMap.put("message", initResultJO.getString("message"));
            restMap.put("taskId", initResultJO.getString("task_id"));

            String data = initResultJO.getString("data");
            if (StringUtils.isNotEmpty(data)) {
                JSONObject dJO = JSON.parseObject(data);
                if (dJO.getString("next_stage") != null) {
                    restMap.put("nextStage", dJO.getString("next_stage"));
                } else {
                    restMap.put("nextStage", nextStage);
                }
                if ("101".equals(restMap.get("code"))) {
                    restMap.put("authCode", dJO.getString("auth_code"));
                }
            } else {
                restMap.put("nextStage", nextStage);
            }
            if ("137".equals(restMap.get("code")) || "2007".equals(restMap.get("code"))) {
//                User user = userService.findLoginUser();
                //授权完毕改变状态
                EntityWrapper<UserAuth> ew3 = new EntityWrapper();
                ew3.eq("user_id", userId);
                UserAuth userAuth = userAuthService.selectOne(ew3);
                userAuth.setPhoneAuth(1);
                userAuthService.updateById(userAuth);
                EntityWrapper<UserPhone> ewPhone = new EntityWrapper();
                ewPhone.eq("user_id", userId);
                UserPhone userPhone = userPhoneService.selectOne(ewPhone);
                //改变user_phone表状态
                userPhone.setStatus(1);
                userPhoneService.updateById(userPhone);

                //总认证通过
                User user=userService.selectById(userId);
                user.setAuthStatus(1);
                userService.updateById(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            log.info("+++++++++++++++++++++++2222222222222222222222222:" + JsonResp.ok(restMap));
            return JsonResp.ok(restMap);
        }
    }

    /**
     * @return void
     * @同盾运营商回调接收接口
     */
    @RequestMapping(value = "/YYSCallBack", method = RequestMethod.POST)
    public String YYSCallBack(HttpServletRequest req) {
        String t = "failed";
        try {
            String notify_data = req.getParameter("notify_data");
            if (notify_data != "") {
                String taskId = JSON.parseObject(notify_data).getString("task_id");
                EntityWrapper ew = new EntityWrapper();
                ew.eq("task_id", taskId);
                YYSLog yysLog = yysLogService.selectOne(ew);
                JSONObject resultJO = TongdunYYSAuth.getAll(taskId);
                if (resultJO != null) {
                    JSONObject data = resultJO.getJSONObject("data");
                    JSONObject taskData = data.getJSONObject("task_data");
                    if (taskData != null) {
                        String callInfo = taskData.getString("call_info");
                        List<String> ciList = JSON.parseArray(callInfo, String.class);
                        for (String a : ciList) {
                            List<UserPhoneRecord> userPhoneRecords = new ArrayList<>();
                            String callRecord = JSON.parseObject(a).getString("call_record");
                            List<String> callList = JSON.parseArray(callRecord, String.class);
                            for (String b : callList) {
                                JSONObject cMap = JSON.parseObject(b);
                                UserPhoneRecord userPhoneRecord = new UserPhoneRecord();
                                userPhoneRecord.setStartTime(cMap.getString("call_start_time"));
                                userPhoneRecord.setCommPlac(cMap.getString("call_address"));
                                userPhoneRecord.setCallType(cMap.getString("call_type_name"));
                                userPhoneRecord.setPhoneNo(cMap.getString("call_other_number"));
                                userPhoneRecord.setConnTimes(cMap.getString("call_time"));
                                userPhoneRecord.setCommMode(cMap.getString("call_land_type"));
                                userPhoneRecord.setCommFee(cMap.getString("call_cost"));
                                userPhoneRecord.setUserId(yysLog.getUserId());
                                userPhoneRecords.add(userPhoneRecord);
                            }

//                            userPhoneRecordService.insertBatch(userPhoneRecords);
                            userPhoneRecordService.saveCall(userPhoneRecords);
                        }

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @return 返回值JsonResp
     * @运营商授权
     */
    //@SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/getAuthPhone", method = RequestMethod.GET)
    public JsonResp getAuthPhone(String phoneNo, String passwd, String capcha, String type, String name, String idCard) throws IOException, InterruptedException {
        log.debug("运营商授权");
        //存储user_phone表
        User user = userService.findLoginUser();
        //User user = userService.selectById(71);
        EntityWrapper<UserPhone> ewPhone = new EntityWrapper();
        ewPhone.eq("user_id", user.getId());
        UserPhone userPhone = userPhoneService.selectOne(ewPhone);
        if (userPhone == null || userPhone.equals("")) {
            userPhone = new UserPhone();
            userPhone.setPhone(phoneNo);
            userPhone.setUserId(user.getId());
            userPhoneService.insert(userPhone);
        } else {
            userPhone.setPhone(phoneNo);
            userPhoneService.updateById(userPhone);
        }
        //回调地址，可不填
        //String callback = "http://666456.tunnel.qydev.com/api/user/getReport?userId="+user.getId()+"";
        String callback = "http://app.hzrywl.com/api/api/user/getReport?userId=" + user.getId() + "";
        String resp = "";
        if (type.equals("第二种方式")) {
            resp = YYSDemo.verifySmsCode(phoneNo, capcha, name, idCard, "");
        } else {
            resp = YYSDemo.login(phoneNo, passwd, capcha, callback);
        }
        JSONObject json = new JSONObject();
        json = json.parseObject(resp);
        String retCode = json.getString("errorCode");
        if (StringUtils.equals(retCode, "0")) {
            Boolean isFinish = json.getBoolean("result");
            if (isFinish) {
                //授权完毕改变状态
                EntityWrapper<UserAuth> ew = new EntityWrapper();
                ew.eq("user_id", user.getId());
                UserAuth userAuth = userAuthService.selectOne(ew);
                userAuth.setPhoneAuth(1);
                userAuthService.updateById(userAuth);
                //改变user_phone表状态
                userPhone.setStatus(1);
                userPhoneService.updateById(userPhone);

                String token = json.getString("token");
                return JsonResp.ok(token);
            } else {
                return JsonResp.fa("请求失败！ | [%s]" + json.getString("errorMsg"));
            }
        } else {
            return JsonResp.fa("请求失败！ | [%s]" + json.getString("errorMsg"));
        }
    }

    /**
     * @return 返回值JsonResp
     * @获取分析报告
     */
    @RequestMapping(value = "/getReport", method = RequestMethod.GET)
    public JsonResp settingPayPwd(String token, String userId) throws IOException {
        log.debug("获取分析报告");
        // 获取报告
        String reqUrl = "http://e.apix.cn/apixanalysis/mobile/retrieve/phone/data/analyzed"; //获取分析报告url
        //String reqUrl = "http://e.apix.cn/apixanalysis/mobile/mobile/life/phone";//获取原始报告url
        JSONObject jsonObject = YYSDemo.getData(reqUrl, token);
        //储存用户通话记录
        User user = userService.selectById(userId);
        Object object = jsonObject.get("callRecordsInfo");
        List<Map> mapList = (List<Map>) object;
        List<UserPhoneRecord> userPhoneRecords = new ArrayList<>();
        if (mapList.size() != 0) {
            for (Map m : mapList) {
                UserPhoneRecord userPhoneRecord = new UserPhoneRecord();
                userPhoneRecord.setUserId(user.getId());
                userPhoneRecord.setBelongArea(m.get("belongArea").toString());
                userPhoneRecord.setCalledTimes(m.get("calledTimes").toString());
                userPhoneRecord.setConnTimes(m.get("connTimes").toString());
                userPhoneRecord.setCallTimes(m.get("callTimes").toString());
                userPhoneRecord.setIdentifyInfo(m.get("identifyInfo").toString());
                userPhoneRecord.setPhoneNo(m.get("phoneNo").toString());
                userPhoneRecord.setType(1);
                userPhoneRecords.add(userPhoneRecord);
            }
            userPhoneRecordService.insertBatch(userPhoneRecords);
        }
        /*else if(serveName.equals("中国联通")){
            Object object = jsonObject.get("phoneDetail");
            List<Map> mapList = (List<Map>) object;
            List<UserPhoneRecord> userPhoneRecords = new ArrayList<>();
            if(mapList.size()==0){
                for(Map m:mapList){
                    UserPhoneRecord userPhoneRecord = new UserPhoneRecord();
                    userPhoneRecord.setUserId(user.getId());
                    userPhoneRecord.setBelongArea(m.get("commPlac").toString());
                    userPhoneRecord.setConnTimes(m.get("commTime").toString());
                    userPhoneRecord.setPhoneNo(m.get("anotherNm").toString());
                    userPhoneRecord.setType(2);
                    userPhoneRecords.add(userPhoneRecord);
                }
                userPhoneRecordService.insertBatch(userPhoneRecords);
            }
        }else if(serveName.equals("中国电信")){
            Object object = jsonObject.get("phoneDetail");
            List<Map> mapList = (List<Map>) object;
            List<UserPhoneRecord> userPhoneRecords = new ArrayList<>();
            if(mapList.size()==0){
                for(Map m:mapList){
                    UserPhoneRecord userPhoneRecord = new UserPhoneRecord();
                    userPhoneRecord.setUserId(user.getId());
                    userPhoneRecord.setCommPhoneNo(m.get("commPhoneNo").toString());
                    userPhoneRecord.setCommTotalTime(m.get("commTotalTime").toString());
                    userPhoneRecord.setCommDate(m.get("commDate").toString());
                    userPhoneRecord.setCommAreaCode(m.get("commAreaCode").toString());
                    userPhoneRecord.setCallType(m.get("callType").toString());
                    userPhoneRecord.setType(3);
                    userPhoneRecords.add(userPhoneRecord);
                }
                userPhoneRecordService.insertBatch(userPhoneRecords);
            }
        }*/


        return JsonResp.ok(jsonObject);
    }

    /**
     * @银行卡认证
     * @return 返回值JsonResp
     */
   /* @SourceAuthority(SourceType.APP)
    @RequestMapping(value="/bankCardAuth", method = RequestMethod.GET)
    public JsonResp bankCardAuth(String type,String bankcardno,String name,String idcardno,String phone) throws IOException {
        log.debug("银行卡认证");
        JSONObject jsonObject = BankCardAuth.request(type,bankcardno,name,idcardno,phone);
        if(jsonObject.get("code").toString().equals("0")){
            //认证完毕改变状态
            User user = userService.findLoginUser();
            EntityWrapper<UserAuth> ew = new EntityWrapper();
            ew.eq("user_id",user.getId());
            UserAuth userAuth =userAuthService.selectOne(ew);
            userAuth.setBankAuth(1);
            userAuthService.updateById(userAuth);
            //判断用户是否完成基本验证
            if(userAuth.getBaiscAuth()==1&&userAuth.getPhoneAuth()==1&&userAuth.getBankAuth()==1&&userAuth.getIdentityAuth()==1&&userAuth.getTaobaoAuth()==1){
                user.setAuthStatus(1);
                user.setAuthScore(60);
                userService.updateById(user);
                //用户数加一
                EntityWrapper<PersonRecord> ewPserson = new EntityWrapper();
                PersonRecord personRecord = personRecordService.selectOne(ewPserson);
                personRecord.setAllCount(personRecord.getAllCount()+1);
                personRecordService.updateById(personRecord);
            }
            //将用户信息存储
            Map data = (Map)jsonObject.get("data");
            Map idcard_data = (Map)jsonObject.get("idcard_data");
            Map phone_data = (Map)jsonObject.get("phone_data");
            //判断之前是否已认证
            EntityWrapper<UserBank> ewBank = new EntityWrapper();
            ewBank.eq("user_id",user.getId());
            UserBank userBank = userBankService.selectOne(ewBank);
            if (userBank==null||userBank.equals("")){
                userBank = new UserBank();
            }
            userBank.setUserId(user.getId());
            userBank.setBankcardno(data.get("bankcardno").toString());
            userBank.setBankName(data.get("bankname").toString());
            userBank.setName(idcard_data.get("name").toString());
            userBank.setCardname(data.get("cardname").toString());
            userBank.setCardtype(data.get("cardtype").toString());
            userBank.setIdcardno(idcard_data.get("idcardno").toString());
            userBank.setAddress(idcard_data.get("address").toString());
            userBank.setBankPhone(phone_data.get("phone").toString());
            userBank.setMobileCity(phone_data.get("mobile_city").toString());
            userBank.setBirthday(idcard_data.get("birthday").toString());
            userBankService.insertOrUpdate(userBank);
            //存入真实姓名
            user.setUserName(idcard_data.get("name").toString());
            userService.updateById( user);
        }
        return JsonResp.ok(jsonObject);
    }*/

    /**
     * @return 返回值JsonResp
     * @银行卡认证
     */
    @SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/bankCardAuth", method = RequestMethod.GET)
    public JsonResp bankCardAuth(String type, String bankcardno, String name, String idcardno, String phone) throws IOException, NoSuchAlgorithmException {
        User user = userService.findLoginUser();
        EntityWrapper ew3 = new EntityWrapper();
        ew3.eq("user_id", user.getId());
        UserAuth ua = userAuthService.selectOne(ew3);
        if (ua.getBaiscAuth() == 1 && ua.getIdentityAuth() == 1 && ua.getPhoneAuth() == 1) {
            Map<String, String> map = new HashMap<>();
            map.put("id_name", name);
            map.put("bank_card_no", bankcardno);
            map.put("id_no", idcardno);
            map.put("mobile", phone);
            map.put("req_type", "01");
            JSONObject jo = TongDunSDKAuth.youDunBank4(JSON.toJSONString(map));
            String ret_code = jo.getJSONObject("header").getString("ret_code");
            if ("000000".equals(ret_code)) {
                JSONObject bodyJO = jo.getJSONObject("body");
                String status = bodyJO.getString("status");
                if ("1".equals(status)) {
                    EntityWrapper<UserAuth> ew = new EntityWrapper();
                    ew.eq("user_id", user.getId());
                    UserAuth userAuth = userAuthService.selectOne(ew);
                    userAuth.setBankAuth(1);
                    userAuthService.updateById(userAuth);
                    //判断之前是否已认证
                    EntityWrapper<UserBank> ewBank = new EntityWrapper();
                    ewBank.eq("user_id", user.getId());
                    UserBank userBank = userBankService.selectOne(ewBank);
                    if (userBank == null) {
                        userBank = new UserBank();
                        userBank.setUserId(user.getId());
                        userBank.setBankcardno(bankcardno);
                        userBank.setName(name);
                        userBank.setIdcardno(idcardno);
                        userBank.setBankPhone(phone);
                        userBank.setCardname(bodyJO.getString("card_name"));
                        userBank.setCardtype(bodyJO.getString("card_type"));
                        userBank.setBankName(bodyJO.getString("org_name"));
                        userBankService.insert(userBank);
                    } else {
                        userBank.setUserId(user.getId());
                        userBank.setBankcardno(bankcardno);
                        userBank.setName(name);
                        userBank.setIdcardno(idcardno);
                        userBank.setBankPhone(phone);
                        userBank.setCardname(bodyJO.getString("card_name"));
                        userBank.setCardtype(bodyJO.getString("card_type"));
                        userBank.setBankName(bodyJO.getString("org_name"));
                        EntityWrapper ew1 = new EntityWrapper();
                        ew1.eq("user_id", user.getId());
                        userBankService.update(userBank, ew1);
                    }
                    //存入真实姓名
                    user.setUserName(name);
                    user.setAuthStatus(1);
                    user.setAuthScore(60);
                    userService.updateById(user);

                    EntityWrapper<UserAuth> ewA = new EntityWrapper();
                    ewA.eq("user_id", user.getId());
//                    UserAuth ua = new UserAuth();
                    ua.setBankAuth(1);
                    userAuthService.update(ua, ewA);
                    return JsonResp.ok("验证成功");
                }
            }

        } else {
            return JsonResp.fa("验证失败");
        }
        return JsonResp.fa("验证失败");
    }


    /**
     * @return 返回值JsonResp
     * @获取社保认证方式
     */
    @RequestMapping(value = "/getShebaoAuthType", method = RequestMethod.GET)
    public JsonResp shebaoAuth(String province_id, String city) throws IOException {
        log.debug("获取社保认证方式");
        JSONObject jsonObject = SheBaoAuth.getCityAndType(province_id);
        //JSONArray jsonArray = new JSONArray();
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        int i = 0;
        for (; i < jsonArray.size(); i++) {
            if (jsonArray.getJSONObject(i).get("city").toString().equals(city)) {
                break;
            }
        }
        Map map = new HashMap();
        map.put("type", jsonArray.getJSONObject(i).get("loginType"));
        map.put("uniqueKey", jsonArray.getJSONObject(i).get("uniqueKey"));
        return JsonResp.ok(map);
        //return JsonResp.ok(jsonObject);
    }

    /**
     * @return 返回值JsonResp
     * @社保认证
     */
    @RequestMapping(value = "/getShebaoAuth", method = RequestMethod.GET)
    public JsonResp getShebaoAuth(String login_type, String unique_key, String loginName, String pwd) throws IOException {
        log.debug("社保认证");
        String params = loginName + "," + pwd;
        JSONObject jsonObject = SheBaoAuth.getConfirm(login_type, unique_key, params);
        //
        if (jsonObject.get("code").toString().equals("0")) {
            //认证完毕改变状态
            User user = userService.findLoginUser();
            EntityWrapper<UserAuth> ew = new EntityWrapper();
            ew.eq("user_id", user.getId());
            UserAuth userAuth = userAuthService.selectOne(ew);
            userAuth.setShebaoAuth(1);
            userAuthService.updateById(userAuth);
        }
        return JsonResp.ok(jsonObject);
    }

    /**
     * @return 返回值JsonResp
     * @淘宝认证
     */
    @RequestMapping(value = "/getTaoBaoAuth", method = RequestMethod.GET)
    public JsonResp getTaoBaoAuth(String success_url, String failed_url) throws IOException {
        log.debug("淘宝认证");
        User user = userService.findLoginUser();
        //String callback_url = "http://666456.tunnel.qydev.com/api/user/getTaoData?userId="+user.getId()+"";
        String callback_url = "http://app.hzrywl.com/api/api/user/getTaoData?userId=" + user.getId() + "";
        JSONObject jsonObject = TaoBaoAuth.getConfirm(callback_url, success_url, failed_url);
        return JsonResp.ok(jsonObject);
    }

    /**
     * @return 返回值JsonResp
     * @淘宝获取数据
     */
    @RequestMapping(value = "/getTaoData", method = RequestMethod.GET)
    public JsonResp getTaoData(String token, String status, String userId) throws IOException {

        log.debug("淘宝获取数据");
        if (!token.equals("") && status.equals("1")) {
            JSONObject jsonObject = TaoBaoAuth.getData(token);
            //认证完毕改变状态
            User user = userService.selectById(userId);
            //User user = userService.selectById(1l);
            EntityWrapper<UserAuth> ew = new EntityWrapper();
            ew.eq("user_id", user.getId());
            UserAuth userAuth = userAuthService.selectOne(ew);
            userAuth.setTaobaoAuth(1);
            userAuthService.updateById(userAuth);
            //存储地址信息
            String addrs = jsonObject.getString("addrs");
            String address = addrs.replace("[", "").replace("]", "");
            String[] addressArray = address.split(",");
            List<UserTaobaoAddress> list = new ArrayList<>();
            for (int i = 0; i < addressArray.length; i++) {
                UserTaobaoAddress userTaobaoAddress = new UserTaobaoAddress();
                userTaobaoAddress.setUserId(user.getId());
                userTaobaoAddress.setAddress(addressArray[i]);
                list.add(userTaobaoAddress);
            }
            userTaobaoAddressService.insertBatch(list);
            //存储支付宝信息
            Map personalInfo = (Map) jsonObject.get("personalInfo");
            UserTaobaoZhifubao userTaobaoZhifubao = new UserTaobaoZhifubao();
            userTaobaoZhifubao.setUserId(user.getId());
            userTaobaoZhifubao.setAlipayRemainingAmount(personalInfo.get("aliPayRemainingAmount").toString());
            userTaobaoZhifubao.setHuabeiCanUseMoney(personalInfo.get("huabeiCanUseMoney").toString());
            userTaobaoZhifubao.setHuabeiTotalAmount(personalInfo.get("huabeiTotalAmount").toString());
            userTaobaoZhifubaoService.insert(userTaobaoZhifubao);
            return JsonResp.ok(jsonObject);
        } else {
            return JsonResp.fa("认证未成功！");
        }
    }

    /**
     * @return 返回值JsonResp
     * @京东认证
     */
    @RequestMapping(value = "/getJingdongAuth", method = RequestMethod.GET)
    public JsonResp getJingdongAuth(String success_url, String failed_url) throws IOException {
        log.debug("京东认证");
        User user = userService.findLoginUser();
        //String callback_url = "http://666456.tunnel.qydev.com/api/user/getJingdongData?userId="+user.getId()+"";
        String callback_url = "http://app.hzrywl.com/api/api/user/getJingdongData?userId=" + user.getId() + "";
        JSONObject jsonObject = JingdongAuth.getConfirm(callback_url, success_url, failed_url);
        return JsonResp.ok(jsonObject);
    }

    /**
     * @return 返回值JsonResp
     * @京东获取数据
     */
    @RequestMapping(value = "/getJingdongData", method = RequestMethod.GET)
    public JsonResp getJingdongData(String token, String status, String userId) throws IOException {
        log.debug("京东获取数据");
        if (!token.equals("") && status.equals("1")) {
            JSONObject jsonObject = JingdongAuth.getData(token);
            //认证完毕改变状态
            //User user = userService.findLoginUser();
            User user = userService.selectById(userId);
            EntityWrapper<UserAuth> ew = new EntityWrapper();
            ew.eq("user_id", user.getId());
            UserAuth userAuth = userAuthService.selectOne(ew);
            userAuth.setJindongAuth(1);
            userAuthService.updateById(userAuth);
            //存储地址信息
            String addrs = jsonObject.getString("orderAddress");
            String address = addrs.replace("[", "").replace("]", "");
            String[] addressArray = address.split(",");
            for (int i = 0; i < addressArray.length; i++) {
                UserJindongAddress userJindongAddress = new UserJindongAddress();
                userJindongAddress.setUserId(user.getId());
                userJindongAddress.setOrderAddress(addressArray[i]);
                userJindongAddressService.insert(userJindongAddress);
            }
            return JsonResp.ok(jsonObject);
        } else {
            return JsonResp.fa("认证未成功！");
        }

    }

    /**
     * @return 返回值JsonResp
     * @获取公积金认证方式
     */
    @RequestMapping(value = "/getGongjijinAuthType", method = RequestMethod.GET)
    public JsonResp getGongjijinAuthType(String province_id, String city) throws IOException {
        log.debug("获取公积金认证方式");
        JSONObject jsonObject = GongjijinAuth.getType(province_id);
        //JSONArray jsonArray = new JSONArray();
/*        JSONArray jsonArray = jsonObject.getJSONArray("data");
        int i=0;
        for (;i<jsonArray.size();i++){
            if(jsonArray.getJSONObject(i).get("city").toString().equals(city)){
                break;
            }
        }
        Map map = new HashMap();
        map.put("note",jsonArray.getJSONObject(i).get("note"));
        map.put("type",jsonArray.getJSONObject(i).get("loginType"));
        map.put("uniqueKey",jsonArray.getJSONObject(i).get("uniqueKey"));*/
        //return JsonResp.ok(map);
        return JsonResp.ok(jsonObject);
    }

    /**
     * @return 返回值JsonResp
     * @公积金认证
     */
    @RequestMapping(value = "/getGongjijinAuth", method = RequestMethod.GET)
    public JsonResp getGongjijinAuth(String login_type, String unique_key, String loginName, String pwd) throws IOException {
        log.debug("公积金认证");
        String params = loginName + "," + pwd;
        JSONObject jsonObject = GongjijinAuth.getConfirm(login_type, unique_key, params);
        //
/*        if(jsonObject.get("code").toString().equals("0")){
            //认证完毕改变状态
            User user = userService.findLoginUser();
            EntityWrapper<UserAuth> ew = new EntityWrapper();
            ew.eq("user_id",user.getId());
            UserAuth userAuth =userAuthService.selectOne(ew);
            userAuth.setGongjijinAuth(1);
            userAuthService.updateById(userAuth);
        }*/
        return JsonResp.ok(jsonObject);
    }

    /**
     * @return 返回值JsonResp
     * @公积金认证H5
     */
    @RequestMapping(value = "/getGongjijinUrl", method = RequestMethod.GET)
    public JsonResp getGongjijinUrl(String success_url, String failed_url) throws IOException {
        log.debug("公积金认证H5");
        String callback_url = "http://www.cctv.com";
        JSONObject jsonObject = GongjijinAuth.getH5PageUrl(callback_url, success_url, failed_url);
        return JsonResp.ok(jsonObject);
    }

    /**
     * @return 返回值JsonResp
     * @公积金获取验证码
     */
    @RequestMapping(value = "/getGongjijinCode", method = RequestMethod.GET)
    public JsonResp getGongjijinCode(String login_type, String unique_key, String login_name) throws IOException {
        log.debug("公积金获取验证码");
        JSONObject jsonObject = GongjijinAuth.getCode(login_type, unique_key, login_name);
        return JsonResp.ok(jsonObject);
    }

    /**
     * @return 返回值JsonResp
     * @公积金获取数据
     */
    @RequestMapping(value = "/getGongjijinData", method = RequestMethod.GET)
    public JsonResp getGongjijinData(String token) throws IOException {
        JSONObject jsonObject = GongjijinAuth.getData(token);
        log.debug("公积金获取数据");
        return JsonResp.ok(jsonObject);
    }


    /**
     * @param page
     * @param phoneNumber
     * @param userName
     * @return 查询黑名单
     */
    @RequestMapping(value = "/selectAllBlackList", method = RequestMethod.GET)
    public JsonResp selectAllBlackList(Page page, String phoneNumber, String userName) {

        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (userName != null && !"".equals(userName)) {
            userEntityWrapper.like("user_name", userName);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        userEntityWrapper.eq("status", 2);
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (!userList.isEmpty()) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageNo", (page.getCurrent() - 1) * page.getSize());
        map.put("pageSize", page.getSize());
        if (ids.size() > 0) {
            map.put("ids", ids);
        }
        int count = loanOrderService.selectBlackListNum(map);
        List<LoanOrder> loanOrderList = loanOrderService.selectBlackList(map);
        if (!loanOrderList.isEmpty()) {
            for (LoanOrder loanOrder : loanOrderList) {
                EntityWrapper<User> userEntityWrapper1 = new EntityWrapper<>();
                userEntityWrapper1.eq("id", loanOrder.getUserId());
                User user1 = userService.selectOne(userEntityWrapper1);
                loanOrder.setUser(user1);
            }
        }
        return JsonResp.ok(new PageDto(page.getCurrent(), page.getSize(), loanOrderList, count));


    }

    /**
     * @param
     * @return 移出黑名单
     */
    @RequestMapping(value = "/moveOutBlackList", method = RequestMethod.GET)
    public JsonResp moveOutBlackList(Long id) {
        // EntityWrapper<User> userEntityWrapper=new EntityWrapper<>();
        User user = new User();
        if (id != null && !"".equals(id)) {
            user = userService.selectById(id);
            user.setStatus(1);
        }
        Boolean bo = userService.updateById(user);
        PersonRecord pr = personRecordService.selectById(1);
        pr.setBlackCount(pr.getBlackCount() - 1);
        Boolean bo1 = personRecordService.updateById(pr);
        Boolean bool = false;
        if (bo && bo1) {
            bool = true;
        }

        return JsonResp.ok(bool);
    }


    /**
     * @return 返回值JsonResp
     * @芝麻认证获取url
     */

    //@SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/getZhiMaUrl", method = RequestMethod.GET)
    public JsonResp getZhiMaUrl(String userName, String idCard, String idCardFront, String idCardBack, String callbackUrl) {
        log.debug("芝麻认证获取url");
        //存储信息
        User user = userService.findLoginUser();
        EntityWrapper<UserIdentity> ewIdentity = new EntityWrapper();
        ewIdentity.eq("user_id", user.getId());
        UserIdentity userIdentity = userIdentityService.selectOne(ewIdentity);
        if (userIdentity == null || userIdentity.equals("")) {
            userIdentity = new UserIdentity();
            userIdentity.setUserId(user.getId());
            userIdentity.setUserName(userName);
            userIdentity.setIdentityBack(idCardBack);
            userIdentity.setIdentityNum(idCard);
            userIdentity.setIdentityFront(idCardFront);
            userIdentityService.insert(userIdentity);
        } else {
            userIdentity.setUserId(user.getId());
            userIdentity.setUserName(userName);
            userIdentity.setIdentityBack(idCardBack);
            userIdentity.setIdentityNum(idCard);
            userIdentity.setIdentityFront(idCardFront);
            userIdentityService.updateById(userIdentity);
        }


        //获取biz_no
        String biz_no = null;
        try {
            biz_no = ZhimaAuth.zhimaCustomerCertificationInitialize(userName, idCard);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!StringUtils.isBlank(biz_no)) {
            //获取url
            String url = null;
            try {
                url = ZhimaAuth.zhimaCustomerCertificationCertify(biz_no, callbackUrl);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Map map = new HashMap();
            map.put("biz_no", biz_no);
            map.put("url", url);
            map.put("userId", user.getId());
            return JsonResp.ok(map);
        } else {
            return JsonResp.fa("获取失败！");
        }
    }

    /**
     * @return 返回值JsonResp
     * @芝麻认证是否通过
     */
    @RequestMapping(value = "/getZhiMaIsPass", method = RequestMethod.GET)
    public JsonResp getZhiMaIsPass(String biz_no, String userId) {
        log.debug("芝麻认证是否通过");
        //String a = JSONObject.parseObject(biz_content).getString("biz_no");
        String sign = null;
        try {
            sign = ZhimaAuth.zhimaCustomerCertificationQuery(biz_no);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (sign.equals("10000")) {
            //认证完毕改变状态
            User user = userService.selectById(userId);
            //User user = userService.selectById(1l);
            EntityWrapper<UserAuth> ewAuth = new EntityWrapper();
            ewAuth.eq("user_id", user.getId());
            UserAuth userAuth = userAuthService.selectOne(ewAuth);
            userAuth.setIdentityAuth(1);
            userAuthService.updateById(userAuth);
            EntityWrapper<UserIdentity> ewIdentity = new EntityWrapper();
            ewIdentity.eq("user_id", user.getId());
            UserIdentity userIdentity = userIdentityService.selectOne(ewIdentity);
            userIdentity.setStatus(1);
            userIdentityService.updateById(userIdentity);
            return JsonResp.ok("已通过验证");
        } else {
            return JsonResp.fa(sign);
        }
    }

    /**
     * @param
     * @return 打款
     */
    @RequestMapping(value = "/payOrder1", method = RequestMethod.GET)
    public JsonResp payByHand1(Long id) {

//        Admin admin = userService.getThisLogin();
//        if (admin != null) {
        log.debug("打款");
        LoanOrder loanOrder = loanOrderService.selectById(id);
        loanOrder.setOrderStatus(3);
        loanOrder.setGiveTime(new Date());
        loanOrderService.updateById(loanOrder);
/*        } else {
        return JsonResp.fa("管理员未登录！");
    }*/

        return JsonResp.ok("打款申请提交成功");
    }

    /**
     * @param
     * @return 打款
     */
    @RequestMapping(value = "/payOrder", method = RequestMethod.GET)
    public JsonResp payByHand(Long id) {
        log.debug("打款");
        Admin admin = userService.getThisLogin();
        if (admin != null) {
            //log.info("+++++++++++++++++++++++++++++++++++++++++++++++++++打款");
            LoanOrder loanOrder = loanOrderService.selectById(id);
            loanOrder.setGiveStatus(1);
            User user = userService.selectById(loanOrder.getUserId());
            EntityWrapper<UserBank> ewBank = new EntityWrapper();
            ewBank.eq("user_id", user.getId());
            UserBank userBank = userBankService.selectOne(ewBank);
            String result = null;
            String orderNo = "RYJDK" + OrderUtils.getOrderNo();
            try {
                result = PaymentApi.payment(orderNo, loanOrder.getRealMoney().toString(), userBank.getBankcardno(), userBank.getBankName(), user.getUserName(), "打款", id);
            } catch (FailException e) {
                return e.getJsonResp();
            } catch (Exception e) {
                e.printStackTrace();
            }
            //log.info("+++++++++++++++++++++++++++++++++++++++++++++++++++打款结果++++++++++++++"+result);
            String[] resultlist = result.split(",");
            if (resultlist[0].equals("success")) {
                loanOrder.setLianPayNum(resultlist[1]);
                loanOrder.setOrderStatus(10);
                loanOrderService.updateById(loanOrder);
                return JsonResp.ok("打款申请提交成功");
            } else if (resultlist[0].equals("needConfirm")) {
                //疑似重复订单
                PayOrderConfirm payOrderConfirm = new PayOrderConfirm();
                payOrderConfirm.setNoOrder(resultlist[1]);
                payOrderConfirm.setCode(resultlist[2]);
                payOrderConfirm.setMoney(loanOrder.getRealMoney().toString());
                payOrderConfirm.setReciveName(user.getUserName());
                payOrderConfirm.setReciveBankNum(userBank.getBankcardno());
                payOrderConfirm.setLoanOrderId(id);
                payOrderConfirmService.insert(payOrderConfirm);
                loanOrder.setLianPayNum(resultlist[1]);
                loanOrderService.updateById(loanOrder);
                return JsonResp.ok("疑似重复订单，请去平台确认！");
            } else if (resultlist[0].equals("fail")) {
                loanOrder.setLianPayNum(resultlist[1]);
                loanOrderService.updateById(loanOrder);
                loanOrder.setGiveStatus(3);
                return JsonResp.fa("打款申请失败！");
            } else {
                loanOrder.setLianPayNum(resultlist[1]);
                loanOrderService.updateById(loanOrder);
                return JsonResp.fa(result);
            }
        } else {
            return JsonResp.fa("管理员未登录！");
        }
    }

    /**
     * @param
     * @return 疑似重复订单确认打款
     */
    @RequestMapping(value = "/payConfirm", method = RequestMethod.GET)
    public JsonResp payConfirmTest(Long id) {
        Admin admin = userService.getThisLogin();
        if (admin != null) {
            PayOrderConfirm payOrderConfirm = payOrderConfirmService.selectById(id);
            payOrderConfirm.setStatus(2);
            payOrderConfirmService.updateById(payOrderConfirm);
            LoanOrder loanOrder = loanOrderService.selectById(payOrderConfirm.getLoanOrderId());
            loanOrder.setOrderStatus(3);
            loanOrder.setGiveStatus(2);
            loanOrderService.updateById(loanOrder);
            String result = null;
            try {
                result = ConfirmPaymentApi.confirmPayment(payOrderConfirm.getNoOrder(), payOrderConfirm.getCode(), id);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (result.equals("success")) {
                return JsonResp.ok("打款申请提交成功");
            } else if (result.equals("fail")) {
                return JsonResp.fa("打款申请失败！");
            } else {
                return JsonResp.fa(result);
            }
        } else {
            return JsonResp.fa("管理员未登录！");
        }
    }

    /**
     * @return 返回值JsonResp
     * @获取确认支付信息
     */
    @SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/getPayMsg", method = RequestMethod.GET)
    public JsonResp getPayMsg(String payPwd) {
        log.debug("获取确认支付信息");
        User user = userService.findLoginUser();
        if (user.getPayPwd().equals(payPwd)) {
            EntityWrapper<LoanOrder> ewOrder = new EntityWrapper();
            ewOrder.eq("user_id", user.getId());
            List<Integer> list = new ArrayList<Integer>() {{
                add(3);
                add(4);
                add(5);
            }};
            ewOrder.in("order_status", list);
            LoanOrder loanOrder = loanOrderService.selectOne(ewOrder);
            EntityWrapper<UserBank> ewBank = new EntityWrapper();
            ewBank.eq("user_id", user.getId());
            UserBank userBank = userBankService.selectOne(ewBank);
            if (loanOrder != null) {
                Map map = new HashMap();
                String orderNo = "RYJHK" + OrderUtils.getOrderNo();
                map.put("no_order", orderNo);
                map.put("money", loanOrder.getNeedPayMoney());
                map.put("bankNum", userBank.getBankcardno());
                map.put("idCard", userBank.getIdcardno());
                map.put("name", user.getUserName());
                map.put("orderId", loanOrder.getId());
                map.put("userId", user.getId());
                //风控参数
                SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                String condition = "{\"frms_ware_category\":\"2010\",\"user_info_mercht_userno\":\"" + user.getId() + "\",\"user_info_dt_register\":\"" + dataFormat.format(user.getGmtDatetime()) + "\",\"user_info_bind_phone\":\"" + user.getPhone() + "\",\"user_info_identify_state\":\"1\",\"user_info_identify_type\":\"1\",\"user_info_full_name\":\"" + userBank.getName() + "\",\"user_info_id_no\":\"" + userBank.getIdcardno() + "\"}";
                map.put("risk_item", condition);
                return JsonResp.ok(map);
            } else {
                return JsonResp.fa("该用户当前无还款订单");
            }
        } else {
            return JsonResp.fa("支付密码不正确");
        }
    }

    /**
     * @return 返回值JsonResp
     * @获取支付界面的信息
     */
    @SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/getPayInterfaceMsg", method = RequestMethod.GET)
    public JsonResp getPayInterfaceMsg() {
        log.debug("获取支付界面的信息");
        User user = userService.findLoginUser();
        EntityWrapper<LoanOrder> ewOrder = new EntityWrapper();
        ewOrder.eq("user_id", user.getId());
        List<Integer> list = new ArrayList<Integer>() {{
            add(3);
            add(4);
            add(5);
        }};
        ewOrder.in("order_status", list);
        LoanOrder loanOrder = loanOrderService.selectOne(ewOrder);
        if (loanOrder != null) {
            Map map = new HashMap();
            map.put("money", loanOrder.getNeedPayMoney());
            map.put("bankNum", loanOrder.getBankCardNum());
            map.put("bankName", loanOrder.getBankName());
            return JsonResp.ok(map);
        } else {
            return JsonResp.fa("该用户当前无还款订单");
        }
    }

    /**
     * @return 返回值JsonResp
     * @获取签约信息
     */
    @SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/getSignMsg", method = RequestMethod.GET)
    public JsonResp getSignMsg(String orderId) {
        log.debug("获取签约信息");
        User user = userService.findLoginUser();
        LoanOrder loanOrder = loanOrderService.selectById(orderId);
        EntityWrapper<UserBank> ewBank = new EntityWrapper();
        ewBank.eq("user_id", user.getId());
        UserBank userBank = userBankService.selectOne(ewBank);
        if (loanOrder != null) {
            Map map = new HashMap();
            String orderNo = "RYJHK" + OrderUtils.getOrderNo();
            map.put("no_order", orderNo);
            map.put("money", loanOrder.getNeedPayMoney());
            map.put("bankNum", userBank.getBankcardno());
            map.put("idCard", userBank.getIdcardno());
            map.put("name", user.getUserName());
            map.put("orderId", loanOrder.getId());
            map.put("userId", user.getId());
            return JsonResp.ok(map);
        } else {
            return JsonResp.fa("该用户当前无还款订单");
        }
    }

    /**
     * @return 返回值JsonResp
     * @签约授权
     */
    @SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/getSignPass", method = RequestMethod.GET)
    public JsonResp getSignPass(String no_agree, String no_order, String user_id, String orderId) throws ParseException {
        log.debug("签约授权");
        String repayment_no = RandomUtils.randomString(7);//还款计划编号
        User user = userService.selectById(user_id);
        LoanOrder loanOrder = loanOrderService.selectById(orderId);
        //存储扣款所需信息
        loanOrder.setLianRepayNum(no_order);
        loanOrder.setNoAgree(no_agree);
        loanOrder.setRepaymentNo(repayment_no);
        loanOrderService.updateById(loanOrder);
        //授权
        String resJson = FenqiPayment.agreenoauthapply(no_agree, repayment_no, loanOrder.getNeedPayMoney().toString(), DateUtils.dateSimple(loanOrder.getLimitPayTime()).toString(), user.getId().toString());
        JSONObject jsonObject = JSONObject.parseObject(resJson);
        if (jsonObject.get("ret_code").toString().equals("0000")) {
            return JsonResp.ok(jsonObject.get("ret_msg").toString());
        } else {
            return JsonResp.fa(jsonObject.get("ret_msg").toString());
        }

    }


    /**
     * @return 返回值JsonResp
     * @用户是否需要还款
     */
    @SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/userIsNeedPay", method = RequestMethod.GET)
    public JsonResp userIsNeedPay() {
        log.debug("用户是否需要还款");
        User user = userService.findLoginUser();
        EntityWrapper<LoanOrder> ewOrder = new EntityWrapper();
        ewOrder.eq("user_id", user.getId());
        List<Integer> list = new ArrayList<Integer>() {{
            add(3);
            add(4);
            add(5);
        }};
        ewOrder.in("order_status", list);
        LoanOrder loanOrder = loanOrderService.selectOne(ewOrder);
        if (loanOrder != null) {
            return JsonResp.ok();
        } else {
            return JsonResp.fa("您的订单还在审核中！");
        }
    }

    /*  *//**
     * @用户是否需要还款
     * @return 返回值JsonResp
     *//*
    @RequestMapping(value="/payByHand", method = RequestMethod.GET)
    public void payByHand() throws ParseException{
        log.info("扣款开始++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        //找到所以要处理的订单
        EntityWrapper<LoanOrder> ewOrder = new EntityWrapper();
        List<Integer> list = new ArrayList<Integer>(){{add(3);add(4);add(5);}};
        ewOrder.in("order_status",list);
        List<LoanOrder> loanOrderList = loanOrderService.selectList(ewOrder);
        if(loanOrderList.size()!=0){
            for(LoanOrder o :loanOrderList){
                if(o.getOrderStatus()==3){
                        log.info("我的扣款开始++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"+o.getRepaymentNo());
                        log.info("userId"+o.getUserId().toString()+"no_order"+o.getLianRepayNum());
                        FenqiPayment.bankcardrepayment(o.getUserId().toString(),o.getLianRepayNum(),o.getRepaymentNo(),o.getNeedPayMoney().toString(),DateUtils.dateSimple(o.getLimitPayTime()).toString(),o.getNoAgree(),o.getId().toString());

                }else{
                    FenqiPayment.bankcardrepayment(o.getUserId().toString(),o.getLianRepayNum(),o.getRepaymentNo(),o.getNeedPayMoney().toString(),DateUtils.dateSimple(o.getLimitPayTime()).toString(),o.getNoAgree(),o.getId().toString());
                }
            }
        }
    }*/

    /**
     * @return 返回值JsonResp
     * @用户是否需要还款
     */
    @RequestMapping(value = "/msg", method = RequestMethod.GET)
    public JsonResp msg() {
        log.debug("用户是否需要还款");
        User user = userService.selectById(32);
        LoanOrder loanOrder = loanOrderService.selectById(335);
        //发送打款成功短信
        EntityWrapper<MsgModel> ewMsg = new EntityWrapper();
        ewMsg.eq("type", 1);
        MsgModel msgModel = msgModelService.selectOne(ewMsg);//找到短信模板
        //将信息部分替换
        String bankNum = loanOrder.getBankCardNum().substring(loanOrder.getBankCardNum().length() - 4, loanOrder.getBankCardNum().length());//银行卡后四位
        String content = msgModel.getContent().replaceAll("</?[^>]+>", "").replace("#userName", user.getUserName()).replace("#number", bankNum).replace("#money", loanOrder.getRealMoney().toString());
        logger.info("短信内容+++++++++++++++++++++++++++++" + content);
        SmsTempletEnum.REMINDSEND.setTypeName(content);
        smsService.smsCodeByType(user.getPhone(), 3);
        return JsonResp.ok(content);
    }


    /**
     * 查询用户是否被永续拒绝
     */
    @RequestMapping(value = "/yx", method = RequestMethod.GET)
    public JsonResp yx() {
        User user = userService.findLoginUser();
        if (user.getStatus() == 5) {
            return JsonResp.ok("false");
        } else {
            return JsonResp.ok("true");
        }
    }


    @RequestMapping(value = "/selectYYSResult", method = RequestMethod.GET)
    public JsonResp selectYYSResult(String userId) {
        EntityWrapper ew = new EntityWrapper();
        ew.eq("user_id", userId);
        YYSLog yysLog = yysLogService.selectOne(ew);
        return JsonResp.ok(yysLog);
    }

    @RequestMapping(value = "/getIDCardAndName", method = RequestMethod.GET)
    public JsonResp getIDCardAndName() {
        User user = userService.findLoginUser();
        EntityWrapper ew = new EntityWrapper();
        ew.eq("user_id", user.getId());
        UserIdentity userIdentity = userIdentityService.selectOne(ew);
        return JsonResp.ok(userIdentity);
    }


    @RequestMapping(value = "/getRefuseTime", method = RequestMethod.GET)
    public JsonResp getRefuseTime() {
        User user = userService.findLoginUser();
        return JsonResp.ok(user.getUptDatetime());
    }

    /**
     * @return 返回值JsonResp
     * @淘宝认证是否通过
     */
    @SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/taoBaoIsPass", method = RequestMethod.GET)
    public JsonResp taoBaoIsPass(String flag, String taskId) {
        log.debug("淘宝认证是否通过");
        User user = userService.findLoginUser();
        EntityWrapper<UserAuth> ew = new EntityWrapper();
        ew.eq("user_id", user.getId());
        UserAuth userAuth = userAuthService.selectOne(ew);
        if (flag.equals("yes")) {
            userAuth.setTaobaoAuth(1);
            userAuthService.updateById(userAuth);
            TbLog tbLog = new TbLog();
            tbLog.setTaskId(taskId);
            tbLog.setUserId(user.getId());
            tbLogService.insert(tbLog);
            return JsonResp.ok();
        } else {
            userAuth.setTaobaoAuth(0);
            userAuthService.updateById(userAuth);
            return JsonResp.fa("");
        }
    }

    /**
     * 淘宝抓取记录
     */
    @Autowired
    private TbLogService tbLogService;

    @RequestMapping(value = "/taoBaoLogSave", method = RequestMethod.GET)
    public JsonResp taoBaoLogSave(String taskId) {
        User user = userService.findLoginUser();
        TbLog tbLog = new TbLog();
        tbLog.setTaskId(taskId);
        tbLog.setUserId(user.getId());
        tbLogService.insert(tbLog);
        return JsonResp.ok("保存成功");
    }


    /**
     * @return 返回json
     * @同盾京东接口 第一阶段
     */
    @RequestMapping(value = "/jdAuth1", method = RequestMethod.GET)
    public JsonResp jdAuth1(String phoneNo, String passwd, Long userId) {
        if (userId == null) {
            return JsonResp.toFail("userId不能为空");
        }
        User user = userService.selectById(userId);
        String phone = user.getPhone();
        Map<String, String> restMap = new HashMap<>();
//        YYSLog t = new YYSLog();
        try {
//            User user = userService.findLoginUser();
            EntityWrapper<UserIdentity> ew = new EntityWrapper();
            ew.eq("user_id", userId);
            UserIdentity userIdentity = userIdentityService.selectOne(ew);
            String idcard = "";
            String userName = "";
            if (userIdentity != null) {
                idcard = userIdentity.getIdentityNum();
                userName = userIdentity.getUserName();
            }
            JSONObject createResultMap = TongdunJDAuth.createTask(userName, idcard, phone);
            Integer code = (Integer) createResultMap.get("code");
            if (createResultMap != null && code == 0) {
   /*             t.setUserId(userId);
                t.setCode(createResultMap.getString("code"));
                t.setMessage(createResultMap.getString("message"));
                t.setTaskId(createResultMap.getString("task_id"));
                JSONObject dataJO = JSON.parseObject(createResultMap.getString("data"));
                t.setMobile(phoneNo);
                t.setCreatedTime(dataJO.getString("created_time"));
                EntityWrapper<YYSLog> ew2 = new EntityWrapper<YYSLog>();
                Map<String,Object> map2 = new HashMap<>();
                map2.put("user_id",t.getUserId());
                yysLogService.deleteByMap(map2);
                yysLogService.insert(t);*/
                JSONObject initResultJO = TongdunJDAuth.acquire(createResultMap.getString("task_id"), phoneNo, passwd, "INIT", "submit", null);
                restMap.put("code", initResultJO.getString("code"));
                restMap.put("message", initResultJO.getString("message"));
                restMap.put("taskId", initResultJO.getString("task_id"));
                String data = initResultJO.getString("data");
                if (StringUtils.isNotEmpty(data)) {
                    JSONObject dJO = JSON.parseObject(data);
                    restMap.put("nextStage", dJO.getString("next_stage"));
                    if ("101".equals(restMap.get("code"))) {
                        restMap.put("authCode", dJO.getString("auth_code"));
                    }
                }
                EntityWrapper<UserJingdong> ewJD = new EntityWrapper();
                ewJD.eq("user_id", userId);
                UserJingdong userJingdong = userJingdongService.selectOne(ewJD);
                if (userJingdong == null || userJingdong.equals("")) {
                    userJingdong = new UserJingdong();
                    userJingdong.setJdAccount(phoneNo);
                    userJingdong.setUserId(userId);
                    userJingdongService.insert(userJingdong);
                } else {
                    userJingdong.setJdAccount(phoneNo);
                    userJingdongService.updateById(userJingdong);
                }

            } else {
                restMap.put("code", createResultMap.getString("code"));
                restMap.put("message", "认证失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            restMap.put("code", "9999");
            restMap.put("message", "系统错误");
        } finally {
            log.info("+++++++++++++++++++++++11111111111111111111111111:" + JsonResp.ok(restMap));
            return JsonResp.ok(restMap);
        }
    }

    /**
     * @return 返回json
     * @同盾京东接口 第二阶段
     */
    @RequestMapping(value = "/jdAuth2", method = RequestMethod.GET)
    public JsonResp jdAuth2(String taskId, String passwd, String nextStage, String code, String txt, String phoneNo, Long userId) {
        Map<String, String> restMap = new HashMap<>();
        try {
            Map<String, String> map = new HashMap<>();
            JSONObject initResultJO = null;
            if ("100".equals(code)) {
                if (nextStage == null || nextStage == "") {
                    nextStage = "LOGIN";
                }
                initResultJO = TongdunJDAuth.acquire(taskId, phoneNo, passwd, nextStage, "query", map);
            } else if ("101".equals(code) || "105".equals(code)) {
                if ("101".equals(code)) {
                    map.put("auth_code", txt);
                } else {
                    map.put("sms_code", txt);
                }
                initResultJO = TongdunJDAuth.acquire(taskId, phoneNo, passwd, nextStage, "submit", map);
            }
            restMap.put("code", initResultJO.getString("code"));
            restMap.put("message", initResultJO.getString("message"));
            restMap.put("taskId", initResultJO.getString("task_id"));

            String data = initResultJO.getString("data");
            if (StringUtils.isNotEmpty(data)) {
                JSONObject dJO = JSON.parseObject(data);
                if (dJO.getString("next_stage") != null) {
                    restMap.put("nextStage", dJO.getString("next_stage"));
                } else {
                    restMap.put("nextStage", nextStage);
                }
                if ("101".equals(restMap.get("code"))) {
                    restMap.put("authCode", dJO.getString("auth_code"));
                }
            } else {
                restMap.put("nextStage", nextStage);
            }
            if ("137".equals(restMap.get("code")) || "2007".equals(restMap.get("code"))) {
//                User user = userService.findLoginUser();
                //授权完毕改变状态
                EntityWrapper<UserAuth> ew3 = new EntityWrapper();
                ew3.eq("user_id", userId);
                UserAuth userAuth = userAuthService.selectOne(ew3);
                userAuth.setJindongAuth(1);
                userAuthService.updateById(userAuth);
                EntityWrapper<UserJingdong> ewJD = new EntityWrapper();
                ewJD.eq("user_id", userId);
                UserJingdong userJingdong = userJingdongService.selectOne(ewJD);
                //改变user_jingdong表状态
                userJingdong.setStatus(1);
                userJingdongService.updateById(userJingdong);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            log.info("+++++++++++++++++++++++2222222222222222222222222:" + JsonResp.ok(restMap));
            return JsonResp.ok(restMap);
        }
    }


/*    public static void main(String[] args) {
        UserController controller=new UserController();
        JSONObject jsonObject=null;
        String access_token="5_b_comkzQEU2wqnVsnvw5NGF03xSYBBSHP5r0GMEQwfN9RLyeuPd4Nd4IHzmgZYy5eK4PpTIFm8O3v9nXG3p8MQ_bVKqvEIdcNklfBV-n5Gw";
        String openId="oMHcQxNoutaUdDmrwhm9J36RE_Cc";
//        jsonObject= controller.getUserMessage(access_token,openId);
        String code="021YQAPc2TqaqD0HmUQc2STAPc2YQAPk";
        System.out.println(controller.getOpenid(code));
//        System.out.println(jsonObject);
    }*/
}



